package com.howie.hmvc.paramparse;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.howie.hmvc.annotations.Valid;
import com.howie.hmvc.exception.ArguErrorException;

public class ParamFloats extends AbsParamParse {
	
	private boolean isValid;
	private boolean required;
	private double minVal;
	private double maxVal;
	
	@Override
	public void init(Annotation[] an) throws Exception {
		Valid valid = getValid(an);
		if(valid != null){
			isValid = true;
			required = valid.required();
			minVal = valid.minVal();
			maxVal = valid.maxVal();
		}
	}
	
	@Override
	public Object getParamter(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String[] values = request.getParameterValues(name);
		if(values == null){
			if(required){
				throw new ArguErrorException(name,"required",null);
			}
		}else{
			Float[] vals = new Float[values.length];
			for(int i=0;i<values.length;i++){
				try {
					vals[i] = Float.parseFloat(values[i]);
				} catch (Exception e) {
					LOG.debug("参数["+name+"]解析出错");
				}
				if(isValid){
					if(vals[i] == null){
						if(required){
							throw new ArguErrorException(name,"required",null);
						}
					}else{
						if(vals[i] < minVal){
							throw new ArguErrorException(name,"minVal",minVal);
						}
						if(vals[i] > maxVal){
							throw new ArguErrorException(name,"maxVal",maxVal);
						}
					}
				}
			}
			return vals;
		}
		return null;
	}
	
}
